package me.zhengjie.modules.hanzi.rest;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.hanzi.domain.HanziCharacter;
import me.zhengjie.modules.hanzi.service.HanziService;
import me.zhengjie.modules.hanzi.service.UserProgressService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import me.zhengjie.utils.Result;

@Slf4j
@Tag(name = "用户进度管理", description = "用户学习进度相关接口")
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserProgressController {
    private final HanziService hanziService;
    private final UserProgressService userProgressService;

    @Operation(summary = "获取用户学习进度")
    @GetMapping("/progress")
    public Result<Map<String, Object>> getUserProgress() {
        Long userId = 1L;
        return Result.ok(userProgressService.getUserProgress(userId));
    }

    @Operation(summary = "更新用户学习进度")
    @PostMapping("/progress")
    public Result<Void> updateProgress(
            @RequestParam String character,
            @RequestParam String status) {
        Long userId = 1L;
        userProgressService.updateProgress(userId, character, status);
        return Result.ok();
    }

    @Operation(summary = "获取用户当前学习阶段的汉字")
    @GetMapping("/characters")
    public Result<List<HanziCharacter>> getUserCharacters() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {
                return Result.error("用户未登录");
            }
            
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String username = userDetails.getUsername();
            
            List<HanziCharacter> characters = hanziService.getUserLearningCharacters(username);
            return Result.ok(characters);
        } catch (Exception e) {
            log.error("获取用户汉字失败", e);
            return Result.error("获取用户汉字失败: " + e.getMessage());
        }
    }
} 